﻿package cn.poco.pepsi.activity.near;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import cn.poco.pepsi.R;
import cn.poco.pepsi.activity.detail.ResDetailActivity_x;
import cn.poco.pepsi.adapter.SearchResultListAdapter;
import cn.poco.pepsi.bean.Dish;
import cn.poco.pepsi.bean.Restaurant;
import cn.poco.pepsi.service.impl.NearImpl;
import cn.poco.pepsi.service.impl.SearchImpl;
import cn.poco.pepsi.util.Cons;
import cn.poco.pepsi.util.GpsLocationUtil;

/**
 * 附近定位，美食列表页
 * @author tanglx
 */
public class NearActivity extends Activity {
	private final static String TAG = "SearchResultActivity";
	private ProgressBar listFooterProgressbar;
	private TextView listFooterTextView;
	private Spinner spinner1, spinner2, spinner3;
	private List<Restaurant> list, list2;
	private List<Dish> listDish;
	private ListView listView;
	private Handler tHandler;
	private String cityCode;
	private SearchResultListAdapter searchListAdapter;
	private GpsLocationUtil nGpsLocationUtil;
	private LinearLayout progress;
	private TextView progressText,titleTextView;
	private Button backBtn;

	// 搜索条件
	private String lat, log;
	private String dishId;
	private String distanceId;
	// 筛选条件
	private Integer dis;
	private Integer vouch;
	// 起始结果
	private int s;
	private int l;

	private SearchImpl searchImpl;
	private NearImpl nearImpl;

	private boolean isFirstOn = true, isLastData = false;

	// 错误处理
	private LinearLayout error;
	private Button tautology;
	private Button setBtn;
	// 无数据处理
	private TextView noDataTextView;
	// 更多
	private LinearLayout viewMore;

	public void initView() {
		// 处理错误信息
		titleTextView=(TextView) findViewById(R.id.show_title);
		titleTextView.setText("附近美食");
		backBtn=(Button) findViewById(R.id.top_left_btn);
		error = (LinearLayout) findViewById(R.id.error);
		error.setVisibility(View.GONE);
		progress = (LinearLayout) findViewById(R.id.progressbar);
		progressText = (TextView) findViewById(R.id.progress_text);
		tautology = (Button) findViewById(R.id.tautology);
		setBtn = (Button) findViewById(R.id.setnet);
		noDataTextView = (TextView) findViewById(R.id.ErrorMessage);

		spinner1 = (Spinner) findViewById(R.id.area_spinner);
		spinner2 = (Spinner) findViewById(R.id.dish_spinner);
		spinner3 = (Spinner) findViewById(R.id.sort_spinner);
		listView = (ListView) findViewById(R.id.listview);

		// 处理传递过来的值
		SharedPreferences sharedPreferences = getSharedPreferences(Cons.GPS_CITY_CODE, MODE_PRIVATE);
		cityCode = sharedPreferences.getString(Cons.CITY_CODE, "000000");
		
		
		s = 0;
		l = 10;
		dishId = null;
		distanceId = "0.5";
		dis = null;
		vouch = null;
		nearImpl = new NearImpl();
		searchImpl = new SearchImpl(this);

		try {
			String[] temp = new String[] { "500米", "1000米", "2000米" };
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner, temp);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinner1.setAdapter(adapter);
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			listDish = searchImpl.getDishs(cityCode, "dish", this);
			String[] temp1 = new String[listDish.size() + 1];
			temp1[0] = "全部菜式";
			for (int j = 0; j < listDish.size(); j++) {
				temp1[j + 1] = listDish.get(j).getName();
			}
			ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.spinner, temp1);
			adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinner2.setAdapter(adapter2);
		} catch (Exception e) {
			e.printStackTrace();
			handler.sendEmptyMessage(Cons.CONN_ERROR);
		}

		try {
			String[] temp = new String[] { "全部", "优惠", "加盟" };
			ArrayAdapter<String> adapte3 = new ArrayAdapter<String>(this, R.layout.spinner, temp);
			adapte3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinner3.setAdapter(adapte3);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 更多的视图
		viewMore = (LinearLayout) LayoutInflater.from(NearActivity.this).inflate(R.layout.list_footer, null);
		listFooterProgressbar = (ProgressBar) viewMore.findViewById(R.id.list_footer_progress);
		listFooterTextView = (TextView) viewMore.findViewById(R.id.list_footer_text);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.search_result);
		initView();

		nGpsLocationUtil = GpsLocationUtil.getInstance(NearActivity.this);
		nGpsLocationUtil.getLocation(handler);
		setStatus(Cons.SHOW_START);
		progressText.setText("正在定位..");

		HandlerThread handlerThread = new HandlerThread(TAG);
		handlerThread.start();
		tHandler = new Handler(handlerThread.getLooper());

		setBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
				startActivity(intent);
			}
		});

		tautology.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
			}
		});
		
		spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				switch (position) {
				case 0:
					distanceId = "0.5";
					break;
				case 1:
					distanceId = "1";
					break;
				case 2:
					distanceId = "2";
					break;
				default:
					break;
				}
				shut();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
		
		spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				switch (position) {
				case 0:
					dishId = null;
					break;
				default:
					dishId = String.valueOf(listDish.get(position - 1).getId());
					break;
				}
				shut();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
		
		spinner3.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				switch (position) {
				case 0:
					vouch = 0;
					dis = 0;
					break;
				case 1:
					dis = 1;
					vouch = 0;
					break;
				case 2:
					dis = 0;
					vouch = 1;
					break;
				default:
					break;
				}
				shut();
			}
			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				int count = listView.getCount();
				if (arg2 == count - 1) {
					s = s + 10;
					listFooterProgressbar.setVisibility(View.VISIBLE);
					listFooterTextView.setText("加载中");
					tHandler.post(runnable2);
				}else {
					Intent intent=new Intent(NearActivity.this,ResDetailActivity_x.class);
					intent.putExtra(Cons.RESDATA, list.get(arg2));
//					intent.putExtra(Cons.RES_CODE, String.valueOf(list.get(arg2).getId()));
					startActivity(intent);
				}
			}
		});

		backBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}

	// spinner加载
	void shut() {
		System.out.println("shut:"+isFirstOn);
		if (isFirstOn==false) {
			tHandler.post(runnable);
			isLastData=false;
			setStatus(Cons.SHOW_START);
			progressText.setText("正在加载数据");
		}
	}

	void setStatus(int i) {
		switch (i) {
		case Cons.SHOW_START://加载中
			progress.setVisibility(View.VISIBLE);
			listView.setVisibility(View.GONE);
			noDataTextView.setVisibility(View.GONE);
			error.setVisibility(View.GONE);
			break;
		case Cons.SHOW_SUCCESS://加载完成
			progress.setVisibility(View.GONE);
			listView.setVisibility(View.VISIBLE);
			noDataTextView.setVisibility(View.GONE);
			error.setVisibility(View.GONE);
			break;
		case Cons.SHOW_NODATA://无数据
			progress.setVisibility(View.GONE);
			listView.setVisibility(View.GONE);
			noDataTextView.setVisibility(View.VISIBLE);
			error.setVisibility(View.GONE);
			break;
		case Cons.SHOW_ERROR://错误
			progress.setVisibility(View.GONE);
			listView.setVisibility(View.GONE);
			noDataTextView.setVisibility(View.GONE);
			error.setVisibility(View.VISIBLE);
			break;
		}
	}
	
	void setSpinner(int i){
		switch (i){
		case 1:
			spinner1.setClickable(false);
			spinner2.setClickable(false);
			spinner3.setClickable(false);
			break;
		case 2:
			spinner1.setClickable(true);
			spinner2.setClickable(true);
			spinner3.setClickable(true);
			break;
		}
	}
	
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Cons.GPS_LOCATION_CHANGE:// 定位成功
				Bundle bundle = msg.getData();
//				lat = String.valueOf(bundle.getDouble(Cons.GPS_LAT, 1));
//				log = String.valueOf(bundle.getDouble(Cons.GPS_LONG, 1));
				lat="23.124547004699036";
				log="113.30414772033362";
				Cons.GPS_LAT_DATA = lat;
				Cons.GPS_LON_DATA =log;
				//Cons.GPS_LAT_DATA = Double.toString(bundle.getDouble(Cons.GPS_LAT));
				//Cons.GPS_LON_DATA = Double.toString(bundle.getDouble(Cons.GPS_LONG));
				nGpsLocationUtil.unRequestListener();
				progressText.setText("正在加载数据...");
				tHandler.post(runnable);
				break;
			case 2://数据加载成功，更新界面
				searchListAdapter = new SearchResultListAdapter(NearActivity.this, list, handler);
				if(isFirstOn&&isLastData==false){
					listView.addFooterView(viewMore);
				}
				listView.setAdapter(searchListAdapter);
				isFirstOn=false;
				setStatus(Cons.SHOW_SUCCESS);
				setSpinner(2);
				break;
			case 3:// 更多更新
				if (isLastData==true) {
					listView.removeFooterView(viewMore);
					Toast.makeText(NearActivity.this, "无更多数据", Toast.LENGTH_SHORT).show();
				} else {
					listFooterProgressbar.setVisibility(View.GONE);
					listFooterTextView.setText("更多");
				}
				searchListAdapter.notifyDataSetChanged();
				break;
			case 4:// 无数据
				setStatus(Cons.SHOW_NODATA);
				break;
			case Cons.CONN_ERROR:// 错误
				setSpinner(1);
				break;
			default:
				break;
			}
		}
	};

	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			try {
				list = nearImpl.getResByGps(cityCode, lat, log, s, l, dis, vouch, dishId, distanceId);
				int size=list.size();
				if(size!=10){
					isLastData=true;
				}
				if (size == 0 || list == null) {
					handler.sendEmptyMessage(4);
				} else {
					handler.sendEmptyMessage(2);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	Runnable runnable2 = new Runnable() {
		@Override
		public void run() {
			try {
				list2 = nearImpl.getResByGps(cityCode, lat, log, s, l, dis, vouch, dishId, distanceId);
				list.addAll(list2);
				int size=list.size();
				if(size<10){
					isLastData=true;
				}
				handler.sendEmptyMessage(3);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

}
